package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.easemob.chat.EMChatManager;
import com.easemob.chatuidemo.activity.RegisterActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;

/**第一次注册-账号注册
 * @author Administrator
 *
 */
public class Register extends Activity {
	private EditText username, password, repassword, phoneno;
	private Button saveButton;
	private ImageButton cancelButton;
	private ProgressDialog proDialog;
	private boolean flag = true;
	InputMethodManager manager;
	private Register oThis = this;

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
				.detectNetwork() // or .detectAll() for all detectable problems
				.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().penaltyLog()
				.penaltyDeath().build());
		setContentView(R.layout.register);
		MyApplication application = (MyApplication) getApplication();
		application.addActivity(this);
		manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		// 得到相应的显示控件的对象
		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
		repassword = (EditText) findViewById(R.id.repassword);
		phoneno = (EditText) findViewById(R.id.phoneno);
		
		username.setOnFocusChangeListener(this.onFocusAutoClearHintListener);
		password.setOnFocusChangeListener(this.onFocusAutoClearHintListener);
		repassword.setOnFocusChangeListener(this.onFocusAutoClearHintListener);
		phoneno.setOnFocusChangeListener(this.onFocusAutoClearHintListener);
		
		saveButton = (Button) findViewById(R.id.save_button);
		cancelButton = (ImageButton) findViewById(R.id.imageback);
		cancelButton.setClickable(true);
		// 为saveButton 注册一个点击事件监听器
		saveButton.setOnClickListener(new View.OnClickListener() {
			// 当按钮被点击时调用该方法
			public void onClick(View v) {
				addUser();
			}
		});

		cancelButton.setOnClickListener(new View.OnClickListener() {
			// 当按钮被点击时调用该方法
			public void onClick(View v) {
				oThis.onBackPressed();
			}
		});
//		Log.e("", application.getDeviceId());
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (getCurrentFocus() != null
					&& getCurrentFocus().getWindowToken() != null) {
				manager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return super.onTouchEvent(event);
	}
	
	public static OnFocusChangeListener onFocusAutoClearHintListener = new OnFocusChangeListener() {
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			EditText textView = (EditText) v;
			String hint;
			if (hasFocus) {
				hint = textView.getHint().toString();
				textView.setTag(hint);
				textView.setHint("");
			} else {
				hint = textView.getTag().toString();
				textView.setHint(hint);
			}
		}
	};

	/**
	* 拼写检测，检测输入内容是否合乎要求
	*/
	public void addUser() {
		int ecolor = Color.RED; // whatever color you want
		String estring = "";
		String name=username.getText().toString().trim();
		String passd=password.getText().toString().trim();
		String moblie=phoneno.getText().toString().trim();
		String repassd=repassword.getText().toString().trim();
		ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
		
		
		if (name.length() == 0) {
			estring = "用户名不能为空";
			SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
			ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
			username.setError(ssbuilder);
		} else if (moblie.length() == 0) {
			estring = "手机号不能为空";
			SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
			ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
			phoneno.setError(ssbuilder);
		}  else if (passd.length() == 0) {
			estring = "密码不能为空";
			SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
			ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
			password.setError(ssbuilder);
		} else if (repassd.length() == 0) {
			estring = "确认密码不能为空";
			SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
			ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
			repassword.setError(ssbuilder);
		} else if (!(repassd.toString()).equals(passd.toString())) {
			estring = "密码不一致";
			SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
			ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
			repassword.setError(ssbuilder);
		} else {
			proDialog = ProgressDialog.show(Register.this, "", "注册中...", true,true);

			String registerInfo = registerUser();
			if (registerInfo.equals("SAVE_SUCCESS")) {
				registerHX(name,passd);

				//				Toast.makeText(Register.this, "注册成功", Toast.LENGTH_SHORT).show();
//				// 到下一页面
//				Intent intent = new Intent();
//				intent.setClass(Register.this, Login.class);
//				startActivity(intent);
			} else if (registerInfo.equals("SAVE_NOTSUCCESS")) {
				Toast.makeText(Register.this, "注册失败", Toast.LENGTH_SHORT).show();
			} else if (registerInfo.equals("SAVE_NAMEUSED")) {
				Toast.makeText(Register.this, "登入帐号已被使用，请重新输入",Toast.LENGTH_SHORT).show();
			}
			proDialog.dismiss();
		}
	}
	
	
	/**
	* 注册环信用户
	*/	
	public void registerHX(final String username,final String pwd) {
		
//			final ProgressDialog pd = new ProgressDialog(this);
//			pd.setMessage("正在注册...");
//			pd.show();
			new Thread(new Runnable() {
				public void run() {
					try {
						// 调用sdk注册方法
						EMChatManager.getInstance().createAccountOnServer(username, pwd);
						runOnUiThread(new Runnable() {
							public void run() {
								// 保存用户名
								MyApplication.getInstance().setUserName(username);
//								Toast.makeText(getApplicationContext(), "注册成功", 0).show();
								Toast.makeText(Register.this, "注册成功", Toast.LENGTH_SHORT).show();
								finish();
								Intent intent = new Intent();
								intent.setClass(Register.this, Login.class);
								startActivity(intent);
							}
						});
					} catch (final Exception e) {
						//医讯通账户删除
						delUser();
						runOnUiThread(new Runnable() {
							public void run() {
								if (e != null && e.getMessage() != null) {
									String errorMsg = e.getMessage();
									if (errorMsg.indexOf("EMNetworkUnconnectedException") != -1) {
										Toast.makeText(getApplicationContext(), "网络异常，请检查网络！", 0).show();
									} else if (errorMsg.indexOf("conflict") != -1) {
										Toast.makeText(getApplicationContext(), "用户已存在！", 0).show();
									
									} else if (errorMsg.indexOf("not support the capital letters") != -1) {
										Toast.makeText(getApplicationContext(), "用户名不支持大写字母！", 0).show();
									} else {
										Toast.makeText(getApplicationContext(), "注册失败: " + e.getMessage(), 1).show();
									}

								} else {
									Toast.makeText(getApplicationContext(), "注册失败: 未知异常", 1).show();

								}
							}
						});
					}
				}
			}).start();

		
	}	
	
	

	/**
	 * 注册用户
	 */
	public String registerUser() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username", username.getText().toString().trim()));
		params.add(new BasicNameValuePair("password", password.getText().toString().trim()));
		params.add(new BasicNameValuePair("phoneno", phoneno.getText().toString().trim()));
		
		JSONObject res = HTTPGetTool.getTool().post(URLUtils.HOSTMAIN + URLUtils.URLREGISTER, params);
		String registerInfo = "SAVE_NOTSUCCESS";
		if (res != null) {
			try {
				registerInfo = res.get("registerInfo").toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return registerInfo;
	}
	
	
	public  String  delUser(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username", username.getText().toString().trim()));
		params.add(new BasicNameValuePair("password", password.getText().toString().trim()));
		params.add(new BasicNameValuePair("phoneno", phoneno.getText().toString().trim()));
		JSONObject res = HTTPGetTool.getTool().post(URLUtils.HOSTMAIN + URLUtils.URLDELUSER, params);
		String registerInfo = "DEL_NOTSUCCESS";
		if (res != null) {
			try {
				registerInfo = res.get("registerInfo").toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return registerInfo;
		
	}
}